const { Controller } = require('egg');

class BillControler extends Controller {
    async create() {
        // 获取参数
        const { type, time, amount, tag, mark } = this.ctx.params;

        //  非空校验
        if (!type || !time || !amount || !tag || !mark) {
            this.ctx.body = {
                code: 400,
                message: '缺少必须参数',
            };
            return;
        }

        // type 只能是：income 收入、expenditure 支出
        if (type !== 'income' && type !== 'expenditure') {
            this.ctx.body = {
                code: 400,
                message: '记账类型只能是：income 或者是 expenditure',
            };
            return;
        }

        // 持久化到数据库
        let res = await this.service.bill.create({
            type,
            time,
            amount,
            tag,
            mark,
        });

        // 判断是否插入成功
        if (res.affectedRows !== 1) {
            this.ctx.body = {
                code: 500,
                message: '记账失败',
            };
            return;
        }

        this.ctx.body = {
            code: 201,
            message: '记账成功',
        };
    }

    /**
     * 获取列表
     */
    async index() {
        let res = await this.service.bill.readList();
        this.ctx.body = {
            code: 200,
            data: res,
            message: '请求成功',
        };
    }
}

module.exports = BillControler;
